#include "SiblingHandle.h"

SiblingHandle::SiblingHandle(void)
{
}

SiblingHandle::~SiblingHandle(void)
{
}

std::vector<std::vector<INTEGER>> SiblingHandle::RetrieveSibling(
	std::vector<INTEGER> left_in, std::vector<INTEGER> right_in)
{
	// Select s such that Sibling (4, s) 
	//       -- returns any s such that Follows*(4,s) or Follows*(s,4)

	std::sort(right_in.begin(), right_in.end());

	std::vector<std::vector<INTEGER>> result_vector;
	std::vector<INTEGER> left_out;
	std::vector<INTEGER> right_out;

	STMT previous_stmt;
	previous_stmt.node_type = _NULL;
	unsigned int i;
	for (i = 0; i < left_in.size(); i++)
	{
		previous_stmt.statement_number = left_in[i];
		STMT_ARRAY sib_temp = PKB::follows.RetrieveTransitiveFollowing(previous_stmt);
		STMT_ARRAY sib_temp2 = PKB::follows.RetrieveTransitivePrevious(previous_stmt);
		
		set_union(sib_temp.begin(), sib_temp.end(),
				      sib_temp2.begin(), sib_temp2.end(),
				      inserter(sib_temp, sib_temp.begin()));

		for(auto it1 = sib_temp.begin(); it1 != sib_temp.end(); it1++)
		{
			INTEGER stmt_num = it1->statement_number;

			if (std::binary_search(right_in.begin(), right_in.end(), stmt_num))
			{
				left_out.push_back(left_in[i]);
				right_out.push_back(stmt_num);
			}
		}
	}

	result_vector.push_back(left_out);
	result_vector.push_back(right_out);
	
	return result_vector;
}